package com.haixiaoke.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.common.exception.ServiceException;
import com.haixiaoke.common.utils.DateUtils;
import com.haixiaoke.domain.SmartLock;
import com.haixiaoke.domain.SmartLockBluetooth;
import com.haixiaoke.domain.SmartLockDetails;
import com.haixiaoke.domain.lockResponse;
import com.haixiaoke.mapper.SmartLockBluetoothMapper;
import com.haixiaoke.mapper.SmartLockMapper;
import com.haixiaoke.service.ISmartLockService;
import com.haixiaoke.smartLock.haixiaoke.SmartLockHXKService;
import com.haixiaoke.smartLock.tianwanghulian.SmartLockTWHlService;
import com.haixiaoke.smartLock.yaluete.SmartLockYLTEventService;
import com.haixiaoke.smartLock.yaluete.SmartLockYLTService;
import com.haixiaoke.smartLock.youdian.SmartLockYdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 智能锁设备Service业务层处理
 *
 * @author xiaolong
 * @date 2023-05-25
 */
@Service
@Slf4j
public class SmartLockServiceImpl implements ISmartLockService {
    @Autowired
    private SmartLockMapper smartLockMapper;
    @Autowired
    private SmartLockTWHlService smartLockTWHlService;
    @Autowired
    private SmartLockBluetoothMapper smartLockBluetoothMapper;
    @Autowired
    private SmartLockYdService smartLockYdService;
    @Autowired
    private SmartLockYLTService smartLockYLTService;
    @Autowired
    private SmartLockHXKService smartLockHXKService;


    /**
     * 查询智能锁设备
     *
     * @param lockId 智能锁设备主键
     * @return 智能锁设备
     */
    @Override
    public SmartLock selectSmartLockByLockId(Long lockId) {
        return smartLockMapper.selectSmartLockByLockId(lockId);
    }

    /**
     * 查询智能锁设备列表
     *
     * @param smartLock 智能锁设备
     * @return 智能锁设备
     */
    @Override
    public List<SmartLock> selectSmartLockList(SmartLock smartLock) {
        List<SmartLock> smartLocks = smartLockMapper.selectSmartLockList(smartLock);
        for (SmartLock lock : smartLocks) {
            if (lock.getBrandId() == SmartLock.THIRD_GENERATION_SMART_LOCK) {
                String result = smartLockYLTService.getSmartLock(lock);
                Object code = JSONObject.parseObject(result).get("code");
                String codeStr = Convert.toStr(code);

                if ("0".equals(codeStr)) {
                    JSONArray jsonArray = JSONObject.parseObject(result).getJSONObject("data").getJSONArray("list");
                    List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                    for (lockResponse lockResponse : javaList) {
                        lock.setConnStatus(lockResponse.getFHwStatus() == 0 ? 1 : 0);
                        Integer fBatVol = lockResponse.getFBatVol();
                        //亚略特电压转电量
                        Integer battery = SmartLockYLTEventService.YLTVoltageConvertBatteryInfo(fBatVol);
                        lock.setBattery(battery);
                        lock.setFwVersion(lockResponse.getFSWVersion());
                        lock.setBluetoothMac(lockResponse.getFMAC());
                        lock.setImei(lockResponse.getFNB_IMEI());
                    }

                }


            } else if (lock.getBrandId() == SmartLock.FOUR_GENERATION_SMART_LOCK) {

                // 调取厂商接口，获取智能锁信息
                String stringResultBean = smartLockTWHlService.getSmartLock(lock);
                Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                if (code == 0) {
                    JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONObject("data").getJSONArray("list");
                    List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                    for (lockResponse lockResponse : javaList) {
                        lock.setLockStatus(lockResponse.getLockStatus());
                        lock.setSignalStrength(lockResponse.getSignalStrength());
                        lock.setConnStatus(lockResponse.getConnStatus());
                        lock.setBattery(lockResponse.getBattery());
                        lock.setFwVersion(lockResponse.getFwVersion());
                        lock.setBluetoothMac(lockResponse.getBluetoothMac());
                        lock.setImei(lockResponse.getImsi());
                    }
                } else {
                    String message = JSONObject.parseObject(stringResultBean).get("msg").toString();
                    log.info("查询优电智能锁信息 = {}", message);
                }
            } else if (lock.getBrandId() == SmartLock.FIVE_GENERATION_SMART_LOCK) {
                lock.setPageNum(1);
                lock.setPageSize(1);
                String result = smartLockHXKService.getSmartLock(lock);
                if (StrUtil.isNotEmpty(result)) {
                    JSONObject resultObject = JSONObject.parseObject(result);
                    String resultData = resultObject.getString("result");
                    if (!"[]".equals(resultData)) {
                        List<lockResponse> jsonObject = JSONArray.parseArray(resultData,lockResponse.class);
                        lock.setBattery(jsonObject.get(0).getBatteryPercent());
                        lock.setFwVersion(jsonObject.get(0).getRomVersion());
                        lock.setBluetoothMac(jsonObject.get(0).getDeviceMac());
                    }
                }
            } else {


                // 获取优电智能锁信息
                String stringResultBean = smartLockYdService.getSmartLock(lock);
                Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                if (code == 0) {
                    JSONObject data = JSONObject.parseObject(stringResultBean).getJSONObject("data");
                    lockResponse javaObject = data.toJavaObject(lockResponse.class);
                    lock.setSignalStrength(javaObject.getSignalLevel() * 20);
                    lock.setBattery(javaObject.getBatteryLevel());
                    lock.setImei(javaObject.getImsi());
                    if (javaObject.getDeviceStatus() == 0) {
                        lock.setConnStatus(1);
                    } else {
                        lock.setConnStatus(0);
                    }
                } else {
                    String message = JSONObject.parseObject(stringResultBean).get("message").toString();
                    log.info("查询优电智能锁信息 = {}", message);
                }
            }

        }
        return smartLocks;
    }

    /**
     * 新增智能锁设备
     *
     * @param smartLock 智能锁设备
     * @return 结果
     */
    @Override
    public int insertSmartLock(SmartLock smartLock) {
        smartLock.setCreateTime(DateUtils.getNowDate());
        return smartLockMapper.insertSmartLock(smartLock);
    }

    /**
     * 修改智能锁设备
     *
     * @param smartLock 智能锁设备
     * @return 结果
     */
    @Override
    public int updateSmartLock(SmartLock smartLock) {
        smartLock.setUpdateTime(DateUtils.getNowDate());
        return smartLockMapper.updateSmartLock(smartLock);
    }

    /**
     * 批量删除智能锁设备
     *
     * @param lockIds 需要删除的智能锁设备主键
     * @return 结果
     */
    @Override
    public int deleteSmartLockByLockIds(Long[] lockIds) {
        return smartLockMapper.deleteSmartLockByLockIds(lockIds);
    }

    /**
     * 删除智能锁设备信息
     *
     * @param lockId 智能锁设备主键
     * @return 结果
     */
    @Override
    public int deleteSmartLockByLockId(Long lockId) {
        return smartLockMapper.deleteSmartLockByLockId(lockId);
    }

    /**
     * 获取智能锁门卡信息
     *
     * @param sn 智能锁SN
     * @return
     */
    @Override
    public List<SmartLockDetails> selectSmartLockBySn(String sn) {
        SmartLock smartLock = new SmartLock();
        smartLock.setSn(sn);
        String stringResultBean = smartLockTWHlService.getSmartLockDetails(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        List<SmartLockDetails> smartLockDetailsList;
        if (code == 0) {
            JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONArray("data");
            smartLockDetailsList = jsonArray.toJavaList(SmartLockDetails.class);
        } else {
            throw new ServiceException("没有该设备信息！");
        }
        return smartLockDetailsList;
    }

    /**
     * 获取智能锁临时密码权限信息
     *
     * @param sn 智能锁SN
     * @return
     */
    @Override
    public List<SmartLockDetails> getLockPassword(String sn) {
        SmartLock smartLock = new SmartLock();
        smartLock.setSn(sn);
        String stringResultBean = smartLockTWHlService.getLockPassword(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        List<SmartLockDetails> smartLockDetailsList;
        if (code == 0) {
            JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONArray("data");
            smartLockDetailsList = jsonArray.toJavaList(SmartLockDetails.class);
        } else {
            throw new ServiceException("没有该设备信息！");
        }
        return smartLockDetailsList;
    }

    /**
     * 获取智能锁临时蓝牙权限信息
     *
     * @param sn 智能锁SN
     * @return
     */
    @Override
    public List<SmartLockDetails> getBluetooth(String sn) {
        SmartLock smartLock = new SmartLock();
        List<SmartLockDetails> list = new ArrayList<>();
        smartLock.setSn(sn);
        String stringResultBean = smartLockTWHlService.getBluetooth(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        List<SmartLockDetails> smartLockDetailsList;
        if (code == 0) {
            JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONArray("data");
            smartLockDetailsList = jsonArray.toJavaList(SmartLockDetails.class);
            for (SmartLockDetails smartLockDetails : smartLockDetailsList) {
                SmartLockDetails details = new SmartLockDetails();
                details.setIdentification(smartLockDetails.getMobile());
                details.setStartTime(smartLockDetails.getValidStart());
                details.setEndTime(smartLockDetails.getValidEnd());
                details.setCreateAt(smartLockDetails.getCreateAt());
                list.add(details);
            }
            return list;
        } else {
            throw new ServiceException("没有该设备信息！");
        }
    }

    /**
     * 删除智能锁蓝牙权限
     *
     * @param sn     智能锁SN
     * @param mobile 蓝牙标识
     * @return
     */
    @Override
    public int deleteBle(String sn, String mobile) {
        SmartLock smartLock = new SmartLock();
        smartLock.setSn(sn);
        smartLock.setIdentification(mobile);
        String stringResultBean = smartLockTWHlService.deleteBle(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        if (code != 0) {
            String msg = (String) JSONObject.parseObject(stringResultBean).get("msg");
            throw new ServiceException(msg);
        }
        return smartLockBluetoothMapper.deleteSmartLockBluetoothBySnAndIdentification(sn, mobile);
    }

    /**
     * 生产离线密码
     *
     * @param smartLock 智能锁设备对象
     * @return
     */
    @Override
    public Map<String, Object> offlinePassword(SmartLock smartLock) {
        String sn = smartLock.getSn();
        Integer passTime = smartLock.getPassTime();
        if (StrUtil.isEmpty(sn)) {
            throw new ServiceException("智能锁sn号不能为空");
        }
        if (StrUtil.isEmpty(smartLock.getIdentification())) {
            throw new ServiceException("智能锁编号不能为空");
        }
        if (passTime == null) {
            throw new ServiceException("有效时间不能为空");
        }
        String stringResultBean = smartLockTWHlService.offlinePassword(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        if (code != 0) {
            String msg = (String) JSONObject.parseObject(stringResultBean).get("msg");
            throw new ServiceException(msg);
        }
        Map<String, Object> Map = new HashMap<>();
        Object password = JSONObject.parseObject(stringResultBean).getJSONObject("data").get("password");
        Map.put("password", password);
        return Map;
    }

    /**
     * 添加胁迫报警密码
     *
     * @param smartLock 智能锁设备对象
     * @return
     */
    @Override
    public String coercionPassword(SmartLock smartLock) {
        return "成功";
    }

    /**
     * 远程开锁（需要先有蓝牙授权）
     *
     * @param smartLock 智能锁设备对象
     * @return
     */
    @Override
    public String remoteUnlock(SmartLock smartLock) {
        String sn = smartLock.getSn();
        String identification = "hongrunting";
        if (StrUtil.isEmpty(sn)) {
            throw new ServiceException("智能锁sn号不能为空");
        }
        // 查询是否有授权蓝牙
        String stringResultBean = smartLockTWHlService.getBluetooth(smartLock);
        Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
        if (code != 0) {
            String msg = (String) JSONObject.parseObject(stringResultBean).get("msg");
            throw new ServiceException(msg);
        }
        JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONArray("data");
        List<SmartLockDetails> smartLockDetailsList = jsonArray.toJavaList(SmartLockDetails.class);
        // 判断是否有蓝牙授权信息
        if (ObjectUtil.isNotNull(smartLockDetailsList)) {
            for (SmartLockDetails smartLockDetails : smartLockDetailsList) {
                // 智能锁标识一致，则说明有蓝牙授权，直接授权远程开锁
                if (smartLockDetails.getMobile().equals(identification)) {
                    smartLock.setIdentification(identification);
                    String resultBean = smartLockTWHlService.remoteUnlock(smartLock);
                    Integer codeInt = (Integer) JSONObject.parseObject(resultBean).get("code");
                    if (codeInt != 0) {
                        String msgStr = (String) JSONObject.parseObject(resultBean).get("msg");
                        throw new ServiceException(msgStr);
                    } else {
                        return "下发成功";
                    }
                }
            }
        }
        //    授权蓝牙开锁
        smartLock.setStartTime(DateUtil.date());
        smartLock.setEndTime(DateUtil.nextMonth());
        smartLock.setIdentification(identification);
        String result = smartLockTWHlService.addBluetooth(smartLock);
        Integer codeBle = (Integer) JSONObject.parseObject(result).get("code");
        if (codeBle != 0) {
            String msgBLe = (String) JSONObject.parseObject(result).get("msg");
            throw new ServiceException(msgBLe);
        } else {
            // 授权远程开锁
            String resultBean = smartLockTWHlService.remoteUnlock(smartLock);
            Integer codeInt = (Integer) JSONObject.parseObject(resultBean).get("code");
            if (codeInt != 0) {
                String msgStr = (String) JSONObject.parseObject(resultBean).get("msg");
                throw new ServiceException(msgStr);
            } else {
                return "下发成功";
            }
        }
    }

    /**
     * 校验智能锁SN号是否唯一
     *
     * @param sn 智能锁sn
     * @return
     */
    @Override
    public boolean checkLockSnUnique(String sn) {
        return smartLockMapper.selectSmartLockBySn(sn) == 0;
    }

    /**
     * 关闭/开启语音播放 状态(0: 关闭;1开启)
     *
     * @param smartLock 智能锁设备对象
     * @return
     */
    @Override
    public int voiceStatus(SmartLock smartLock) {
        return smartLockMapper.updateSmartLock(smartLock);
    }

    /**
     * 根据智能锁SN号查询智能锁信息
     *
     * @param sn 智能锁SN号
     * @return
     */
    @Override
    public SmartLock selectBySn(String sn) {
        return smartLockMapper.selectBySn(sn);
    }

    @Override
    public int deleteSmartLockBySn(String sn) {
        return smartLockMapper.deleteSmartLockBySn(sn);
    }

    @Override
    public List<SmartLock> selectSmartLockListBySns(List<String> sns) {
        List<SmartLock> smartLocks = smartLockMapper.selectSmartLockListBySns(sns);
        for (SmartLock lock : smartLocks) {
            if (lock.getBrandId() == SmartLock.THIRD_GENERATION_SMART_LOCK) {
                String result = smartLockYLTService.getSmartLock(lock);
                Object code = JSONObject.parseObject(result).get("code");
                String codeStr = Convert.toStr(code);

                if ("0".equals(codeStr)) {
                    JSONArray jsonArray = JSONObject.parseObject(result).getJSONObject("data").getJSONArray("list");
                    List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                    for (lockResponse lockResponse : javaList) {
                        Integer fBatVol = lockResponse.getFBatVol();
                        //亚略特电压转电量
                        Integer battery = SmartLockYLTEventService.YLTVoltageConvertBatteryInfo(fBatVol);
                        lock.setBattery(battery);
                    }

                }


            } else if (lock.getBrandId() == SmartLock.FOUR_GENERATION_SMART_LOCK) {

                // 调取厂商接口，获取智能锁信息
                String stringResultBean = smartLockTWHlService.getSmartLock(lock);
                Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                if (code == 0) {
                    JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONObject("data").getJSONArray("list");
                    List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                    for (lockResponse lockResponse : javaList) {
                        lock.setBattery(lockResponse.getBattery());
                    }
                } else {
                    String message = JSONObject.parseObject(stringResultBean).get("msg").toString();
                    log.info("查询优电智能锁信息 = {}", message);
                }
            } else if (lock.getBrandId() == SmartLock.FIVE_GENERATION_SMART_LOCK) {
                lock.setPageNum(1);
                lock.setPageSize(1);
                String result = smartLockHXKService.getSmartLock(lock);
                if (StrUtil.isNotEmpty(result)) {
                    JSONObject resultObject = JSONObject.parseObject(result);
                    String resultData = resultObject.getString("result");
                    if (!"[]".equals(resultData)) {
                        List<lockResponse> jsonObject = JSONArray.parseArray(resultData,lockResponse.class);
                        lock.setBattery(jsonObject.get(0).getBatteryPercent());
                    }
                }
            } else {


                // 获取优电智能锁信息
                String stringResultBean = smartLockYdService.getSmartLock(lock);
                Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                if (code == 0) {
                    JSONObject data = JSONObject.parseObject(stringResultBean).getJSONObject("data");
                    lockResponse javaObject = data.toJavaObject(lockResponse.class);
                    lock.setBattery(javaObject.getBatteryLevel());
                } else {
                    String message = JSONObject.parseObject(stringResultBean).get("message").toString();
                    log.info("查询优电智能锁信息 = {}", message);
                }
            }

        }
        return smartLocks;
    }

    @Override
    public Map<String, Object> homePage(List<String> sns) {
        List<SmartLock> smartLocks = smartLockMapper.selectSmartLockListBySns(sns);
        LocalDateTime now = LocalDateTime.now();
        int lowBattery = 0;
        int offLine = 0;
        if (CollectionUtil.isNotEmpty(smartLocks)) {
            for (SmartLock lock : smartLocks) {
                if (lock.getBrandId() == SmartLock.THIRD_GENERATION_SMART_LOCK) {
                    String result = smartLockYLTService.getSmartLock(lock);
                    Object code = JSONObject.parseObject(result).get("code");
                    String codeStr = Convert.toStr(code);

                    if ("0".equals(codeStr)) {
                        JSONArray jsonArray = JSONObject.parseObject(result).getJSONObject("data").getJSONArray("list");
                        List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                        for (lockResponse lockResponse : javaList) {
                            Integer fBatVol = lockResponse.getFBatVol();
                            //亚略特电压转电量
                            Integer battery = SmartLockYLTEventService.YLTVoltageConvertBatteryInfo(fBatVol);
                            lock.setBattery(battery);
                        }
                    }
                } else if (lock.getBrandId() == SmartLock.FOUR_GENERATION_SMART_LOCK) {
                    // 调取厂商接口，获取智能锁信息
                    String stringResultBean = smartLockTWHlService.getSmartLock(lock);
                    Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                    if (code == 0) {
                        JSONArray jsonArray = JSONObject.parseObject(stringResultBean).getJSONObject("data").getJSONArray("list");
                        List<lockResponse> javaList = jsonArray.toJavaList(lockResponse.class);
                        for (lockResponse lockResponse : javaList) {
                            lock.setBattery(lockResponse.getBattery());
                        }
                    } else {
                        String message = JSONObject.parseObject(stringResultBean).get("msg").toString();
                        log.info("查询优电智能锁信息 = {}", message);
                    }
                } else if (lock.getBrandId() == SmartLock.FIVE_GENERATION_SMART_LOCK) {
                    lock.setPageNum(1);
                    lock.setPageSize(1);
                    String result = smartLockHXKService.getSmartLock(lock);
                    if (StrUtil.isNotEmpty(result)) {
                        JSONObject resultObject = JSONObject.parseObject(result);
                        String resultData = resultObject.getString("result");
                        if (!"[]".equals(resultData)) {
                            List<lockResponse> jsonObject = JSONArray.parseArray(resultData,lockResponse.class);
                            if (jsonObject.get(0).getBatteryPercent() <= 20) {
                                lowBattery++;
                            }
                            // 解析最后修改时间并计算与当前时间的差值
//                            LocalDateTime lastUpdateTime = LocalDateTime.parse(jsonObject.get(0).getModifyTime(),
//                                    DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                            long hoursDiff = ChronoUnit.HOURS.between(jsonObject.get(0).getModifyTime(), now);
                            if (hoursDiff > 4) {
                                offLine++;
                            }
                        }
                    }
                } else {
                    // 获取优电智能锁信息
                    String stringResultBean = smartLockYdService.getSmartLock(lock);
                    Integer code = (Integer) JSONObject.parseObject(stringResultBean).get("code");
                    if (code == 0) {
                        JSONObject data = JSONObject.parseObject(stringResultBean).getJSONObject("data");
                        lockResponse javaObject = data.toJavaObject(lockResponse.class);
                        lock.setBattery(javaObject.getBatteryLevel());
                    } else {
                        String message = JSONObject.parseObject(stringResultBean).get("message").toString();
                        log.info("查询优电智能锁信息 = {}", message);
                    }
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("lowBattery", lowBattery);
        map.put("offLine", offLine);
        return map;
    }
}
